﻿using System;
using System.Reflection;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace SilverMenu
{
	public class SilverMenuContentManager : ContentManager
	{
		public SilverMenuContentManager(IServiceProvider serviceProvider, string rootDirectory) : base(serviceProvider, rootDirectory)
        {
        }

		public override T Load<T>(string assetName)
		{
			if (typeof(T) == typeof(SilverMenu))
			{
				SilverMenu menu = base.Load<SilverMenu>(assetName);
				foreach (var page in menu.Pages)
				{
					foreach (var elem in page.Value.Elements)
					{
						if (elem is SilverBackground)
							((SilverBackground)elem).Texture = base.Load<Texture2D>(elem.Source);
						else if (elem is SilverButton)
						{
							SilverButton btn = elem as SilverButton;
                            if(!String.IsNullOrEmpty(btn.Source))
							    btn.Texture = base.Load<Texture2D>(btn.Source);

                            if(btn.FontSource != null)
							    btn.Font = base.Load<SpriteFont>(btn.FontSource);

							if (!String.IsNullOrEmpty(btn.EventHandlerName))
							{
								int index = btn.EventHandlerName.LastIndexOf('.');
								if (index <= 0)
									throw new ArgumentException("The Event handler name must be complete: Namespace.ClassName.MethodName");

                                //TODO: IMPLEMENT THIS
							}
						}
						else if (elem is SilverText)
							((SilverText)elem).Font = base.Load<SpriteFont>(elem.Source);
					}
				}

				return (T)(object)menu;
			}
				
			return Load<T>(assetName);
		}
	}
}
